//
//  HJEditGroupInfoController.m
//  KaiChat
//
//  Created by lx on 2023/11/7.
//

#import "HJEditGroupInfoController.h"
#import "QMUITextView.h"
#import "QMUITextField.h"
#import "HJUIAlertController.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "HJIM.h"
#import "TOCropViewController.h"

@interface HJEditGroupInfoController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, QMUITextViewDelegate, TOCropViewControllerDelegate, QMUITextFieldDelegate>

@property (nonatomic, weak) UILabel *nameLengthLabel;
@property (nonatomic, weak) QMUITextField *nameTextField;

@property (nonatomic, weak) UILabel *introduceLengthLabel;
@property (nonatomic, weak) QMUITextView *introduceTextView;
@property (nonatomic, assign) NSInteger nameMaxLenght;
@property (nonatomic, assign) NSInteger introduceMaxLenght;
@property (nonatomic, weak) UIImageView *avatarImageView;
@property (nonatomic, copy) NSString *imageUrl;
@property (nonatomic, weak) HJStyle1Button *doneButton;
@property (nonatomic, assign) BOOL isModify;


@end

@implementation HJEditGroupInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _nameMaxLenght = 20;
    _introduceMaxLenght = 60;
    
    self.navigationBar.title = @"Edit Group Information";
    self.navigationBar.lineView.hidden = YES;
    
    UIImageView *avatarImageView = [UIImageView addToView:self.view];
    avatarImageView.addCornerRadius(40);
    [avatarImageView addTapGesturesWithTarget:self action:@selector(didClickAvatarImageView)];
    [avatarImageView tj_setImageWithUrl:self.groupModel.avatar placeholderImage:[UIImage imageNamed:defaultAvatarName]];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20 + KNavBarHight);
        make.width.height.offset(80);
        make.centerX.offset(0);
    }];
    
    UIButton *editButton = [UIButton addToView:self.view];
    [editButton setImage:[UIImage imageNamed:@"takePhoto"] forState:UIControlStateNormal];
    [editButton setImage:[UIImage imageNamed:@"takePhoto"] forState:UIControlStateHighlighted];
    [editButton addTarget:self action:@selector(didClickAvatarImageView) forControlEvents:UIControlEventTouchUpInside];
    [editButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(avatarImageView);
        make.bottom.equalTo(avatarImageView);
        make.width.height.offset(28);
    }];
    
    UILabel *nameLabel = [UILabel lableWithSuperView:self.view font:UIFontMediumMake(14) color:UIColor.tj_333333Color title:@"Group Name" textAlignment:NSTextAlignmentLeft];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.top.equalTo(avatarImageView.mas_bottom).offset(22);
    }];
    
    UIView *nameView = [UIView addToView:self.view];
    nameView.addCornerRadius(10);
    nameView.backgroundColor = UIColor.tj_F6F6F6Color;
    [nameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLabel);
        make.right.inset(leftRightMargin);
        make.top.equalTo(nameLabel.mas_bottom).offset(10);
        make.height.offset(50);
    }];
    
    QMUITextField *nameTextField = [QMUITextField addToView:nameView];
    nameTextField.text = self.groupModel.name;
    nameTextField.font = UIFontMake(14);
    nameTextField.delegate = self;
    nameTextField.textColor = UIColor.tj_333333Color;
    nameTextField.placeholder = @"Group Name";
    nameTextField.maximumTextLength = _nameMaxLenght;
    nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [nameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.top.bottom.offset(0);
        make.right.inset(60);
    }];
    
    UILabel *nameLengthLabel = [UILabel lableWithSuperView:nameView font:UIFontMake(12) color:UIColor.tj_BEBDCAColor title:nil textAlignment:NSTextAlignmentLeft];
    [nameLengthLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(15);
        make.centerY.offset(0);
    }];
    
    UILabel *introduceLabel = [UILabel lableWithSuperView:self.view font:UIFontMediumMake(14) color:UIColor.tj_333333Color title:@"Group Introduction" textAlignment:NSTextAlignmentLeft];
    [introduceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.top.equalTo(nameView.mas_bottom).offset(20);
    }];
    
    UIView *introduceView = [UIView addToView:self.view];
    introduceView.addCornerRadius(10);
    introduceView.backgroundColor = UIColor.tj_F6F6F6Color;
    [introduceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(introduceLabel);
        make.right.inset(leftRightMargin);
        make.top.equalTo(introduceLabel.mas_bottom).offset(10);
        make.height.offset(90);
    }];
    
    QMUITextView *introduceTextView = [QMUITextView addToView:introduceView];
    introduceTextView.text = self.groupModel.intro;
    introduceTextView.textColor = UIColor.tj_333333Color;
    introduceTextView.font = UIFontMake(14);
    introduceTextView.tintColor = UIColor.tj_mainColor;
    introduceTextView.placeholderColor = UIColor.tj_placeholderTextColor;
    introduceTextView.placeholder = groupDefaultIntroduce;
    introduceTextView.backgroundColor = UIColor.tj_F6F6F6Color;
    introduceTextView.maximumTextLength = _introduceMaxLenght;
    [introduceTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.top.offset(8);
        make.bottom.offset(0);
        make.right.inset(10);
    }];
    
    UILabel *introduceLengthLabel = [UILabel lableWithSuperView:introduceView font:UIFontMake(12) color:UIColor.tj_BEBDCAColor title:nil textAlignment:NSTextAlignmentLeft];
    [introduceLengthLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(15);
        make.bottom.inset(10);
    }];
    
    HJStyle1Button *doneButton = [HJStyle1Button buttonWithSuperView:self.view font:UIFontMediumMake(14) color:nil title:@"Done"];
    [doneButton addTarget:self action:@selector(didClickDoneButton) forControlEvents:UIControlEventTouchUpInside];
    [doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(introduceView);
        make.height.offset(buttonHeight);
        make.bottom.inset(10 + TabbarSafeBottomMargin);
    }];
    
    _avatarImageView = avatarImageView;
    _nameLengthLabel = nameLengthLabel;
    _nameTextField = nameTextField;
    _introduceTextView = introduceTextView;
    _introduceLengthLabel = introduceLengthLabel;
    _doneButton = doneButton;
    
    self.imageUrl = self.groupModel.avatar;
    [self textFieldDidChange:_nameTextField];
    [self updateIntroduceLengthLabelText];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextChanged:) name:UITextViewTextDidChangeNotification object:introduceTextView];
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 获取新的文本
      NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
      // 去除字符串开头和结尾的空格
      NSString *trimmedString = [newText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
      // 判断新的文本与去除空格后的文本是否相等，如果不相等，则说明用户尝试在开头或结尾输入空格
      if (![newText isEqualToString:trimmedString]) {
          // 如果是空格，则不允许输入
          if ([string isEqualToString:@" "]) {
              return NO;
          } else if ([string isEqualToString:@""] && range.length > 0) {// 如果是删除操作，且删除的是开头或结尾的空格，则允许删除
              return YES;
          } else { // 其他情况，不允许输入
              return NO;
          }
      }
      return YES;
}

- (void)didClickAvatarImageView {
    
    HJUIAlertController *alert = [HJUIAlertController alertControllerWithTitle:nil message:nil preferredStyle:HJUIAlertControllerStyleActionSheet];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Camera" style:HJUIAlertActionStyleDefault handler:^(HJUIAlertAction * _Nonnull action) {
        AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
            [self alertWithTitle:nil message:@"Camera permission is not enabled Go to settings to turn on camera permissions" leftButtonName:@"Cancel" rightButtonName:@"OK" leftButtonBlock:^{
            } rightButtonBlock:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }];
            return;
        }
        [self chooseFromCamera];
    }]];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Photo" style:HJUIAlertActionStyleDefault handler:^(HJUIAlertAction * _Nonnull action) {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
            [self alertWithTitle:nil message:@"Gallery permission is not enabled Go to settings to turn on gallery permissions" leftButtonName:@"Cancel" rightButtonName:@"OK" leftButtonBlock:^{
            } rightButtonBlock:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }];
            return;
        }
        [self chooseFromPhotoAlbum];
    }]];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Cancel" style:HJUIAlertActionStyleCancel handler:^(HJUIAlertAction * _Nonnull action) {
        
    }]];
    
    [alert showInViewController:self];
}


- (void)chooseFromPhotoAlbum {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}


- (void)chooseFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        //        imagePickerController.allowsEditing = YES;
        imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = (UIImage *)info[UIImagePickerControllerOriginalImage];
    
    
    TOCropViewController *cropViewController = [[TOCropViewController alloc] initWithImage:image];
    cropViewController.delegate = self;
    cropViewController.doneButtonColor = UIColor.whiteColor;
    cropViewController.cancelButtonColor = UIColor.whiteColor;
    cropViewController.doneButtonTitle = @"Done";
    cropViewController.cancelButtonTitle = @"Cancel";
    cropViewController.rotateClockwiseButtonHidden = YES;
    cropViewController.aspectRatioPickerButtonHidden = YES;
    cropViewController.resetButtonHidden = YES;
    cropViewController.aspectRatioPickerButtonHidden = YES;
    cropViewController.rotateClockwiseButtonHidden = YES;
    cropViewController.rotateButtonsHidden = YES;
    cropViewController.aspectRatioLockEnabled = YES;
    cropViewController.minimumAspectRatio = 1.0;
    cropViewController.aspectRatioPreset = TOCropViewControllerAspectRatioPresetSquare;
    [picker presentViewController:cropViewController animated:YES completion:nil];
    
}

- (void)cropViewController:(nonnull TOCropViewController *)cropViewController
            didCropToImage:(nonnull UIImage *)image withRect:(CGRect)cropRect
                     angle:(NSInteger)angle {
    TJWeakify(self)
    [cropViewController dismissToRootViewController:YES completion:^{
        [weakself uploadImageWithImage:image];
    }];
    
}

- (void)uploadImageWithImage:(UIImage *)image {
    
    [HJHUD showLoadingInView:self.view text:nil];
    
    [image asynImageSize:CGSizeMake(60, 60) color:UIColor.whiteColor finishiBlock:^(UIImage *drawImage) {
        
        NSString *objectKey = getUploadFileKey(HJFileTypeImage, [NSString stringWithFormat:@"%@.%@", [NSString stringWithFormat:@"%.f", NSDate.date.timeIntervalSince1970 * 1000].md5, @"jpeg"]);
        [HJNetworking.shareNetwork uploadImageWithObejctKey:objectKey fileData:UIImageJPEGRepresentation(drawImage, 0.7) progress:nil success:^(NSString * _Nonnull url) {
            self.imageUrl = url;
            self.avatarImageView.image = image;
            self.isModify = YES;
            [self updateDoneButtonState];
            [HJHUD hiddenLoading];

        } failure:^(NSError * _Nonnull error) {
            
        }];
    }];
    
}


- (BOOL)isValidGroupName:(NSString *)groupName {
    NSString *pattern = @"^[a-zA-Z0-9][a-zA-Z0-9 ]*$";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
    NSRange range = NSMakeRange(0, groupName.length);
    NSTextCheckingResult *result = [regex firstMatchInString:groupName options:0 range:range];
    return result != nil;
}

- (void)didClickDoneButton {
    
    NSString *name = _nameTextField.text;
    if (isEmptyString(name)) {
        name = self.groupModel.name;
    }
    
    [HJHUD showLoadingInView:self.view];
    
    [HJIM.shareIM.groupManager editGroupInfoByGroupId:self.groupModel.groupId avatar:self.imageUrl name:name intro:_introduceTextView.text completion:^(HJChatGroupModel * _Nullable groupModel) {
        if (groupModel) {

            if (self.imageUrl) {
                NSString *key = [SDWebImageManager.sharedManager cacheKeyForURL:self.imageUrl.URL];
                [SDImageCache.sharedImageCache storeImage:self.avatarImageView.image forKey:key toDisk:YES completion:^{
                    dispatch_async_main_queue(^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:refreshGroupInfoNotification object:groupModel];
                        [self.navigationController popViewControllerAnimated:YES];
                        [HJHUD showSucceedMessageTip];
                    });
                }];
            } else {
                [[NSNotificationCenter defaultCenter] postNotificationName:refreshGroupInfoNotification object:groupModel];
                [self.navigationController popViewControllerAnimated:YES];
                [HJHUD showSucceedMessageTip];
            }
        } else {
            [HJHUD showErrorMessageTip];
        }
    }];
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    [self updateDoneButtonState];
    _isModify = YES;
    
    if ( _nameTextField.text.length > 0) {
        _nameLengthLabel.attributedText = [[NSString stringWithFormat:@"%ld/%ld", _nameTextField.text.length, _nameMaxLenght] attributedStringWithRangeString:[NSString stringWithFormat:@"%ld", _nameTextField.text.length] rangeColor:UIColor.tj_333333Color color:UIColor.tj_868391Color];
    } else {
        _nameLengthLabel.attributedText = [[NSString stringWithFormat:@"%ld/%ld", _nameTextField.text.length, _nameMaxLenght] attributedStringWithRangeString:[NSString stringWithFormat:@"%ld", _nameTextField.text.length] rangeColor:UIColor.tj_868391Color color:UIColor.tj_868391Color];
    }
}

- (void)updateDoneButtonState {
    _doneButton.enabled = _nameTextField.text.length && !isEmptyString(_nameTextField.text) && _isModify;
}

- (void)handleTextChanged:(NSNotification *)not {
    if (not.object != _introduceTextView) return;
    _isModify = YES;
    [self updateDoneButtonState];
    [self updateIntroduceLengthLabelText];
}

- (void)updateIntroduceLengthLabelText {
    if ( _introduceTextView.text.length > 0) {
        _introduceLengthLabel.attributedText = [[NSString stringWithFormat:@"%ld/%ld", _introduceTextView.text.length, _introduceMaxLenght] attributedStringWithRangeString:[NSString stringWithFormat:@"%ld", _introduceTextView.text.length] rangeColor:UIColor.tj_333333Color color:UIColor.tj_868391Color];
    } else {
        _introduceLengthLabel.attributedText = [[NSString stringWithFormat:@"%ld/%ld", _introduceTextView.text.length, _introduceMaxLenght] attributedStringWithRangeString:[NSString stringWithFormat:@"%ld", _introduceTextView.text.length] rangeColor:UIColor.tj_868391Color color:UIColor.tj_868391Color];
    }
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:_introduceTextView];
}

@end

